package com.cloud.sso.web;

import com.cloud.sso.common.config.SSOProperty;
import com.cloud.sso.common.exception.AppException;
import com.cloud.sso.common.log.annoatation.BusinessLog;
import com.cloud.sso.dto.UpdatePasswordDto;
import com.cloud.sso.dto.UserQueryDto;
import com.cloud.sso.dto.UserSaveDto;
import com.cloud.sso.entity.User;
import com.cloud.sso.oauth.obj.AppUserDetails;
import com.cloud.sso.oauth.service.AppUserDetailService;
import com.cloud.sso.common.result.Result;
import com.cloud.sso.service.RoleService;
import com.cloud.sso.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author teng
 * 用户处理类
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private AppUserDetailService appUserDetailService;

    @Autowired
    private SSOProperty ssoProperty;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserService userService;

    /**
     * 分页查询用户信息
     *
     * @param user
     * @return
     */
    @RequestMapping("/query")
    public Result queryByPage(@RequestBody UserQueryDto user) {
        return Result.success(userService.queryByPage(user));
    }

    /**
     * 搜索用户
     *
     * @param userName
     * @return
     */
    @RequestMapping("/search")
    public Result search(@RequestParam String userName) {
        return Result.success(userService.search(userName));
    }


    /**
     * 新增保存用户信息
     *
     * @param user
     * @return
     */
    @BusinessLog(value = "新增用户", module = "用户管理", field = "realName", type = "INSERT")
    @RequestMapping("/save")
    public Result saveUser(@RequestBody UserSaveDto user) {
        userService.save(user);
        return Result.success(1);
    }

    /**
     * 查询用户详情
     *
     * @param id
     * @return
     */
    @RequestMapping("/get")
    public Result<User> get(@RequestParam String id) {
        return Result.success(userService.get(id));
    }

    /**
     * 修改用户信息
     *
     * @param user
     * @return
     */
    @BusinessLog(value = "修改用户", module = "用户管理", field = "realName", type = "UPDATE")
    @RequestMapping("/update")
    public Result updateUser(@RequestBody UserSaveDto user) {
        userService.save(user);
        return Result.success(1);
    }

    /**
     * 重置密码
     *
     * @param id
     * @return
     */
    @BusinessLog(value = "重置用户密码", module = "用户管理", field = "id", type = "UPDATE")
    @RequestMapping("/reset/password")
    public Result resetPassword(@RequestParam String id) {
        userService.resetPassword(id);
        return Result.success(1);
    }

    /**
     * 修改密码
     *
     * @param dto
     * @return
     */
    @BusinessLog(value = "修改用户密码", module = "用户管理", field = "userId", type = "UPDATE")
    @RequestMapping("/update/password")
    public Result updatePassword(@RequestBody UpdatePasswordDto dto) {
        userService.updatePassword(dto);
        return Result.success(1);
    }

    /**
     * 修改用户状态
     *
     * @param id
     * @return
     */
    @BusinessLog(value = "修改用户状态", module = "用户管理", type = "UPDATE")
    @RequestMapping("/update/state")
    public Result updateState(@RequestParam String id) {
        userService.updateState(id);
        return Result.success(1);
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @BusinessLog(value = "删除用户", module = "用户管理", field = "id", type = "DELETE")
    @RequestMapping("/delete")
    public Result saveUser(@RequestParam String id) {
        userService.delete(id);
        return Result.success(1);
    }

    /**
     * 获取当前登陆用户信息
     *
     * @return
     */
    @RequestMapping("/info")
    public Result<AppUserDetails> list(HttpServletRequest request) {
     /* 问题记录：通过下面方法获取到authentication为Null，目前未解决
        SecurityContext securityContext = SecurityContextHolder.getContext();

        Authentication authentication = securityContext.getAuthentication();

        AppUserDetails appUserDetails = appUserDetailService.getCurrentUserDetails();
        */
        HttpSession httpSession = request.getSession();
        SecurityContext securityContext = (SecurityContext) httpSession.getAttribute("SPRING_SECURITY_CONTEXT");

        if (securityContext == null) {
            throw new AppException("当前用户未登录");
        }
        Authentication authentication = securityContext.getAuthentication();

        if (authentication == null) {
            throw new AppException("当前用户未登录");
        } else {

            AppUserDetails appUserDetails = (AppUserDetails) authentication.getPrincipal();
            appUserDetails.setPassword(null);
            if (!appUserDetails.getSysManage().equals(ssoProperty.getSysManagerFlag())) {
                throw new AppException("该用户不是系统管理员");
            }

            return Result.success(appUserDetails);
        }
    }

    @RequestMapping("/configure")
    public Result<Map> configure() {
        Map<String, String> map = new HashMap<>();

        map.put("loginUrl", ssoProperty.getLoginUrl());
        map.put("logoutUrl", ssoProperty.getLogoutUrl());

        return Result.success(map);
    }

}
